﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections;
using System.Data.SqlClient;

public partial class forgotpassword : System.Web.UI.Page
{
    DataTable dt_ngCompanyUser = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack && tb_userID.Text != "")
        {
            security hds = new security(tb_userID.Text.Replace("'", "''"));
            HDDatabase HDD = new HDDatabase(Session["servercon"].ToString());
            dt_ngCompanyUser = HDD.GetDataTable("select usr.*, com.[af_row_id] as company_af_row_id from [ngcompanyuser] usr inner join [ngcompany] com on com.[company_id] = usr.[company_id] where usr.[user_id] = '" + tb_userID.Text.Replace("'", "''") + "' order by usr.[company_id] asc;");
            if (dt_ngCompanyUser != null && dt_ngCompanyUser.Rows.Count > 1 && dd_companyId.SelectedValue == "")
            {
                dt_ngCompanyUser.Rows.InsertAt(dt_ngCompanyUser.NewRow(), 0);
                dd_companyId.DataSource = dt_ngCompanyUser;
                dd_companyId.DataTextField = "company_id";
                dd_companyId.DataValueField = "company_af_row_id";
                dd_companyId.DataBind();
            }
        }
    }
    protected void bt_continue_with_userId_Click(object sender, EventArgs e)
    {
        try
        {
            div_userId.Visible = false;
            bt_continue_with_userId.Visible = false;
            if (dt_ngCompanyUser == null || dt_ngCompanyUser.Rows.Count == 0)
            {
                //lbl_userid_err.Text = "Invalid user. User does not exists.";
                showMessage("An email has been sent to your mail id, including the instructions to reset your password. Please check your email to proceed with the reset request.");
                return;
            }
            if (dt_ngCompanyUser.Rows.Count > 1)
            {
                div_companyId.Visible = true;
                bt_continue_with_companyId.Visible = true;
            }
            else
                GenerateForgotPwdEmail(dt_ngCompanyUser.Rows[0]["company_id"].ToString(), tb_userID.Text.Replace("'", "''"), dt_ngCompanyUser.Rows[0]["company_af_row_id"].ToString(), dt_ngCompanyUser.Rows[0]["af_row_id"].ToString());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: bt_continue_with_userId_Click: Error: " + ex.Message);
            showMessage("Unable to process your request now. Please try later.");
        }
    }
    protected void bt_continue_with_companyId_Click(object sender, EventArgs e)
    {
        try
        {
            div_companyId.Visible = false;
            bt_continue_with_companyId.Visible = false;
            GenerateForgotPwdEmail(dd_companyId.SelectedItem.Text, tb_userID.Text.Replace("'", "''"), dd_companyId.SelectedItem.Value, dt_ngCompanyUser.Select("company_af_row_id = '" + dd_companyId.SelectedItem.Value + "'")[0]["af_row_id"].ToString());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: bt_continue_with_companyId_Click: Error: " + ex.Message);
            showMessage("Unable to process your request now. Please try later.");
        }
    }

    private void GenerateForgotPwdEmail(string sCompany_id, string sUser_id, string sCompany_row_id, string sUser_row_id)
    {
        ScreenReader SR = new ScreenReader();
        CommonFunctions objCmnFun = new CommonFunctions();
        string sUserEmailId, sForgotPwdID, sForgotPasswordMailContent, user_fname, sFromMailID;
        try
        {
            sForgotPwdID = SR.getHashKey();
            if (!WriteForgotPasswordLog(sCompany_row_id, sUser_row_id, sForgotPwdID)) return;
            if (validateActiveUser(sCompany_id, sUser_id))
            {
                DataRow[] dr = dt_ngCompanyUser.Select("company_id = '" + sCompany_id + "'");
                if (dr[0]["hint_question"].ToString() != "" && dr[0]["hint_answer"].ToString() != "")
                {
                    sUserEmailId = getUserEmailID(sUser_id);
                    if (objCmnFun.ValidateEmailID(sUserEmailId))
                    {
                        HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
                        user_fname = hdd.GetColumnValue("select [first_name] from [sy_usr] where [af_row_id] = '" + sUser_row_id + "';");
                        sFromMailID = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where af_row_id='b13034b44961ff77';");
                        sForgotPasswordMailContent = ReadHtmFile();
                        sForgotPasswordMailContent = sForgotPasswordMailContent.Replace("$user$", user_fname);
                        sForgotPasswordMailContent = sForgotPasswordMailContent.Replace("$path$", Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "resetpassword.aspx?qr=" + sForgotPwdID);
                        sForgotPasswordMailContent = sForgotPasswordMailContent.Replace("\r\n", "");
                        SentInEmailQueue(sUserEmailId, sFromMailID, true, sForgotPasswordMailContent.Replace("'", "''"), "MaxBlox - Reset Forgotten Password");
                        showMessage("An email has been sent to '" + sUserEmailId + "' including the instructions to reset your password. Please check your email to proceed with the reset request.");
                    }
                    else
                        Response.Redirect("resetpassword.aspx?qr=" + sForgotPwdID);
                }
                else
                    showMessage("Hint question and answer not specified for this user. Please contact your administrator.");
            }
            else
                showMessage("Your account is inactive. Please contact your administrator.");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: GenerateForgotPwdEmail: Error: " + ex.Message);
            showMessage("Unable to process your request now. Please try later.");
        }
        finally
        {
            SR = null;
            objCmnFun = null;
        }
    }

    private bool validateActiveUser(string strCompanyId, string user_id)
    {
        bool ret = false;
        try
        {
            HDDatabase HDD = new HDDatabase(Session["servercon"].ToString());
            DataTable dt = HDD.GetDataTable("select * from ngcompanyserver where company_id='" + strCompanyId.Replace("'", "''") + "'");
            if (dt.Rows.Count < 1) dt = HDD.GetDataTable("select * from ngcompanyserver where company_id = (select [af_row_id] from [ngcompany] where [company_id] = '" + strCompanyId.Replace("'", "''") + "')");
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + strCompanyId + @""";Password=""" + strCompanyId + @"_123"";Initial Catalog="""
                            + row["dbname"].ToString() + @"""";
                HDDatabase hdtemp = new HDDatabase(strConn);
                if (hdtemp.isValidConnection())
                {
                    DataTable dtuser = hdtemp.GetDataTable("select * from sy_usr where user_id = '" + user_id + "'");
                    if (dtuser != null && dtuser.Rows.Count > 0)
                        if (dtuser.Columns.Contains("active") && Convert.ToBoolean(dtuser.Rows[0]["active"].ToString()))
                            ret = true;
                        else if (dtuser.Rows[0]["af_row_id"].ToString() == "650a333596bbf348")
                            ret = true;
                    Session["dbcon"] = strConn;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: validateActiveUser: Error: " + ex.Message);
        }
        return ret;
    }
    
    private string getUserEmailID(string sUserID)
    {
        string sRet = "";
        try
        {
            HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
            DataRow dr = hdd.GetTableRow("select [mem_value2] as table_name, [mem_value3] as field_name from [sy_acr_mem] where [acr_id] = '30e5b719afe1e5be' and [af_row_id] = '76bc31960d22cc50' and [mem_value1] = 'enabled';");
            if (dr == null) return sRet;
            sRet = hdd.GetColumnValue("select " + dr["field_name"].ToString() + " from " + dr["table_name"].ToString() + " where user_id = '" + sUserID + "';");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: getUserEmailID: Error: " + ex.Message);
        }
        return sRet;
    }

    private bool WriteForgotPasswordLog(string sCompany_id, string sUser_id, string sForgotPwdID)
    {
        bool sRet = false;
        SqlCommand sqlCommand = null;
        SqlConnection sqlConn = null;
        try
        {
            string sSql = "INSERT INTO [sy_forgot_password_log] ([company_id],[user_id],[active],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                 " VALUES ('" + sCompany_id + "','" + sUser_id + "',1,'" + sForgotPwdID +
                 "','e51e0327224a2eb9','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','e51e0327224a2eb9', 'e51e0327224a2eb9');";
            sqlConn = new SqlConnection(Session["servercon"].ToString());
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            if (sqlCommand.ExecuteNonQuery() > 0)
                sRet = true;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("forgotpassword: WriteForgotPasswordLog : Error : " + ex.Message);
        }
        finally
        {
            if (sqlCommand != null)
                sqlCommand.Dispose();
            if (sqlConn != null)
            {
                if (sqlConn.State.Equals(ConnectionState.Open))
                    sqlConn.Close();
                sqlConn.Dispose();
            }
        }
        return sRet;
    }
    public string ReadHtmFile()
    {
        string fileName = Server.MapPath("") + "/ForgotPasswordMailContent.htm";
        string content;
        FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        content = reader.ReadToEnd();
        reader.Close();
        return content;
    }
    private bool SentInEmailQueue(string sToEmailID, string sFromMailID, bool isHTML, string content, string subject)
    {
        bool sRet = false;
        ScreenReader SR = new ScreenReader();
        SqlConnection SqlCon = null;
        SqlCommand sqlCmd = null;
        try
        {
            string sConn = HttpContext.Current.Session["servercon"].ToString();
            HDDatabase Hdd = new HDDatabase(sConn);

            string strQuery = "INSERT INTO [email_queue] ([to_address],[from_address],[isHTML],[subject],[content],[priority],[delivery],[created_at],[row_id],[bcc_address]) " +
                "VALUES ('" + sToEmailID + "','" + sFromMailID + "'," + (isHTML ? 1 : 0) + ",'" + subject + "','" + content + "',0,'" + DateTime.Now.ToUniversalTime() + "','" + DateTime.Now.ToUniversalTime() + "','" + SR.getHashKey() + "','')";

            SqlCon = new SqlConnection(sConn);
            sqlCmd = new SqlCommand(strQuery, SqlCon);
            int execute = Hdd.ExecuteCmdObj(sqlCmd);
            if (execute > 0) sRet = true;
            Hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SentInEmailQueue :" + ex.Message);
            return false;
        }
        finally
        {
            if (SqlCon != null)
            {
                if (SqlCon.State.Equals(ConnectionState.Open))
                    SqlCon.Close();
                SqlCon.Dispose();
            }
            if (sqlCmd != null)
                sqlCmd.Dispose();
            SR = null;
        }
        return sRet;
    }
    private void showMessage(string sMsg)
    {
        div_error.Visible = true;
        lbl_validate_info.Text = sMsg;
        lbl_img_req.Visible = false;
    }
}
